/* 
 * File:   GuiContainer.cpp
 * Author: pson
 * 
 * Created on April 15, 2011, 1:44 PM
 */

#include "GuiContainer.h"
#ifdef DEBUG_NEW
#include "debug/debug_new.h"
#endif

GuiContainer::GuiContainer() {

}

GuiContainer::GuiContainer(GuiRect* rect, GuiProp* prop): GuiWidget(rect, prop) {
    
}

GuiContainer::~GuiContainer() {
    for (list<GuiWidget*>::iterator it = _children.begin(); it != _children.end(); ++it) {
        delete *it;
    }
}

void GuiContainer::add_child(GuiWidget* w) {
    float z = w->prop()->zindex;
    w->set_parent(this);
    if (_children.empty() || z >= _children.back()->prop()->zindex) {
        _children.push_back(w);
    } else {
        for (list<GuiWidget*>::iterator it = _children.begin(); it != _children.end(); ++it) {
            if (z > (*it)->prop()->zindex) {
                _children.insert(++it, w);
                break;
            }
        }
    }
    redraw();
}

void GuiContainer::remove_child(GuiWidget* w) {
    _children.remove(w);
    redraw();
}

void GuiContainer::validate() {
    if (_parent) {
        _rect->validate(_parent->_rect->value());
    }
    for (list<GuiWidget*>::iterator it = _children.begin();
            it != _children.end(); ++it) {
        (*it)->validate();
    }
}
//
//list<GuiWidget*>* GuiContainer::get_children() {
//    return &_children;
//}

void GuiContainer::input(SDL_Event* evt, unsigned int ms) {
    for (list<GuiWidget*>::reverse_iterator rit = _children.rbegin();
            rit != _children.rend(); ++rit) {
        (*rit)->input(evt, ms);
    }
}

void GuiContainer::update(unsigned int ms) {
    for (list<GuiWidget*>::iterator it = _children.begin();
            it != _children.end(); ++it) {
        (*it)->update(ms);
    }
}

void GuiContainer::draw(FontManager* font) {
    for (list<GuiWidget*>::iterator it = _children.begin();
            it != _children.end(); ++it) {
        (*it)->draw(font);
    }
}